package com.mairuide.one_click_search.controller;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide._frame.utils.ThreadPoolUtils;
import com.mairuide.entity.Result;
import com.mairuide.entity.StatusCode;
import com.mairuide.one_click_search.dto.DataTemplateDto;
import com.mairuide.one_click_search.pojo.DataTemplate;
import com.mairuide.one_click_search.pojo.DataTemplateField;
import com.mairuide.one_click_search.pojo.OnekeyImportLog;
import com.mairuide.one_click_search.service.DataSourceService;
import com.mairuide.one_click_search.service.DataTemplateService;
import com.mairuide.one_click_search.service.OneKeyWorkTask;
import com.mairuide.one_click_search.service.OnekeyImportLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Description
 * @auther 刘中华
 * @create 2019-04-24 9:31
 */
@Controller
@RequestMapping("onekey")
public class DataTemplateController extends BaseController {

    @ModuleCode( value = "onekey")
    @RequestMapping(method= RequestMethod.GET,value = "index")
    public Object index(){
        return "/one_click_search/index";
    }

    @RequestMapping(method= RequestMethod.GET,value = "addPage")
    public Object addPage(){
        request.setAttribute("vid",0);
        return "/one_click_search/add";
    }
    @RequestMapping(method= RequestMethod.GET,value = "updatePage/{vid}")
    public Object updatePage(@PathVariable(name = "vid") Integer vid){
        request.setAttribute("vid",vid);
        return "/one_click_search/add";
    }
    @RequestMapping("/import")
    public Object importDataTemplate(){
        return "/one_click_search/importOneKeySearch";
    }
    @RequestMapping("/export")
    public Object exportDataTemplate(){
        return "/one_click_search/exportOneKey";
    }
    @RequestMapping("/list")
    public Object listTemplate(){
        return "/one_click_search/list";
    }

    @Autowired
    private DataTemplateService dataTemplateService;

    @Autowired
    private OnekeyImportLogService onekeyImportLogService;
    @Autowired
    DataSourceService dataSourceService;
    /**
     * @Author 刘中华
     * @Date 2019/4/24 9:33
     * @Param [dataTemplateDto]
     * @return com.mairuide.entity.Result
     * @Description  新增、修改模板  已弃用！
     **/
    @RequestMapping("/add")
    @ResponseBody
    public Result saveDataTemplate(@RequestBody DataTemplateDto dataTemplateDto){
        dataTemplateService.addDataTemplate(dataTemplateDto);
        return new Result(true, StatusCode.OK,"操作成功");
    }

    /**
     * @Author 刘中华
     * @Date 2019/4/28 10:50
     * @Param [dataTemplate]
     * @return com.mairuide.entity.Result
     * @Description  新增 修改模板
     **/
    @RequestMapping("/addTemplate")
    @ResponseBody
    public Result saveDataTemplate(@RequestBody DataTemplate dataTemplate){
        try {
            dataTemplateService.saveTemplate(dataTemplate);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"操作失败");
        }
        return new Result(true, StatusCode.OK,"操作成功");
    }

    @RequestMapping("/findTemplateById/{vid}")
    @ResponseBody
    public Result findTemplateById(@PathVariable(name = "vid") Integer vid){
        DataTemplate template = dataTemplateService.findDataTemplateById(vid);
        return new Result(true, StatusCode.OK,"操作成功",template);
    }

    @RequestMapping("/findTemplateDtoById/{vid}")
    @ResponseBody
    public Result findTemplateDtoById(@PathVariable(name = "vid") Integer vid){
        DataTemplateDto templateDto = dataTemplateService.findDataTemplateDtoById(vid);
        return new Result(true, StatusCode.OK,"操作成功",templateDto);
    }

    /**
     * @Author 刘中华
     * @Date 2019/4/24 9:34
     * @Param [vid]
     * @return com.mairuide.entity.Result
     * @Description 删除模板
     **/
    @RequestMapping("del/{vid}")
    @ResponseBody
    public Result delDataTemplate(@PathVariable Integer vid){
        dataTemplateService.delDataTemplate(vid);
        return new Result(true, StatusCode.OK,"操作成功");
    }

    /**
     * @Author 刘中华
     * @Date 2019/4/24 16:04
     * @Param [files, vid]
     * @return com.mairuide.entity.Result
     * @Description  上传一键搜的excel
     **/
    @RequestMapping("uploadFile")
    @ResponseBody
    public Result importDataSource(@RequestParam("fileUpload") MultipartFile[] files,DataTemplateDto dataTemplateDto){
        try {
            String uuid = null;
            List resultList = new ArrayList();
            Integer vid = dataTemplateDto.getVid();
            if (vid==null){
                return new Result(false, StatusCode.ERROR,"导入失败");
            }
            DataTemplate dataTemplate = dataTemplateService.findOneById(vid);
            Map<String, DataTemplateField> dataTemplateFieldMap = dataTemplateService.getDataTemplateFieldMap(vid);
            Map<String , Object> paramMap = new HashMap<String , Object>();
            paramMap.put("dataTemplateFieldMap",dataTemplateFieldMap);
            paramMap.put("dataTemplate",dataTemplate);
            paramMap.put("platManagerId",super.getLoginUser().getId());
            //容器存放提交给线程池的任务
            BlockingQueue<Future<Map<String, Object>>> queue =
                    new LinkedBlockingQueue<Future<Map<String, Object>>>();
            for (int i = 0; i < files.length; i++) {
                uuid = UUID.randomUUID().toString();
                paramMap.put("uuid",uuid);
                paramMap.put("excelName",files[i].getOriginalFilename());
                Future<Map<String, Object>> future = ThreadPoolUtils.getInstance().getThreadPool().submit(new OneKeyWorkTask(files[i], paramMap));
                queue.add(future);
            }
            // 检查线程池任务执行结果
            for (int i = 0; i < files.length; i++) {
                Map<String, Object> map = queue.take().get();
                if (map!=null){
                    resultList.add(map);
                    OnekeyImportLog onekeyImportLog = new OnekeyImportLog();
                    onekeyImportLog.setCreateId(super.getLoginUser().getId());
                    onekeyImportLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    onekeyImportLog.setCreateName(super.getLoginUser().getLoginName());
                    onekeyImportLog.setIsDelete(0);
                    onekeyImportLog.setMobanname(dataTemplate.getMobanname());
                    onekeyImportLog.setUuid(uuid);
                    onekeyImportLog.setImportFailedNum(0);
                    onekeyImportLog.setTablename(dataTemplate.getTablename());
                    onekeyImportLog.setImportSuccessNum(map.get("successNum")==null?null:Integer.valueOf(map.get("successNum").toString()));
                    onekeyImportLog.setFilename(files[i].getName());
                    onekeyImportLogService.saveOnekeyImportLog(onekeyImportLog);
                }
            }
            //导入完成之后调一下solr的同步接口
            dataSourceService.synchronizationSolrData();
            return new Result(true, StatusCode.OK,"导入成功",resultList);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR,"导入失败");
    }

    /**
     * @Author 刘中华
     * @Date 2019/4/25 14:48
     * @Param []
     * @return com.mairuide.entity.Result
     * @Description  查找所有的模板对象
     **/
    @RequestMapping("listAll")
    @ResponseBody
    public Result getListDataTemplate(){
        List<DataTemplate> templateList = dataTemplateService.findAll();
        return new Result(true, StatusCode.OK,"操作成功",templateList);
    }
    /**
     * @Author 刘中华
     * @Date 2019/4/26 11:24
     * @Param []
     * @return com.mairuide.entity.Result
     * @Description  得到分页对象
     **/
    @RequestMapping("/search/{page}/{size}")
    @ResponseBody
    public Result getPageDataTemplate(DataTemplateDto dataTemplateDto,@PathVariable int page, @PathVariable int size){
        Page<DataTemplate> pageData = dataTemplateService.getPageData(dataTemplateDto, page, size);
        return new Result(true, StatusCode.OK,"操作成功",pageData);
    }


}
